package global

import (
	"mygo/mystruct"
	"mygo/mymongo"
	"mygo/mylog"
	"path/filepath"
	"encoding/json"
	"strings"
	"os"
	"fmt"
	"time"
)

var Mtoken mystruct.Mytoken


func Init() {
	ex, err := os.Executable()
	if err != nil{
		panic(fmt.Errorf("os.Executable函数启动失败: %w", err))
	}
	args := os.Args
	var mpath string
	tempDir := os.TempDir()
	// 判断是否位于临时目录中
	if strings.HasPrefix(args[0], tempDir) {
		fmt.Println(fmt.Sprintf("调试启动: %s",time.Now().Format("2006-01-02 15:04:05"))) 
		currentdir, _ := os.Getwd()
		mpath = currentdir
	} else {
		mpath = filepath.Dir(ex)
	}

	Mtoken = mystruct.Mytoken{ 
		Log_Path: filepath.Join(mpath, "log"),
	    Download_Path: filepath.Join(mpath, "download"),
	    File_Path: filepath.Join(mpath, "web", "file"),
	    Main_Path: mpath,
	    Web_Path: filepath.Join(mpath, "web"),
	}
	err = mystruct.ReadJSONFile(&Mtoken)
	if err != nil {
		mylog.ErrLog(err.Error(), Mtoken.Log_Path)
		panic(err)
	}

	err = mymongo.Myinit(mpath) //初始化mongodb
	if err != nil {
		mylog.ErrLog(fmt.Sprintf("数据库初始化失败: %s", err.Error()), Mtoken.Log_Path)
		panic(fmt.Errorf("数据库初始化失败: %w", err))
	}
	
	
    Mtoken.Initcode, err = mystruct.Encrypt(time.Now().Format("20060102150405"), Mtoken.Key) 
    
    mystruct.WriteJSONFile(&Mtoken)

    // 目录初始化
    for _, dir := range []string{Mtoken.Log_Path, Mtoken.Download_Path, Mtoken.File_Path} {
	    if mystruct.Exists(dir) == false {
	    	if err := os.MkdirAll(dir, os.ModePerm); err != nil{
	    		mylog.ErrLog(fmt.Sprintf("创建目录失败: %s", err.Error()), Mtoken.Log_Path)
	    		panic(fmt.Errorf("创建目录失败: %w", err))
	    	}
	    }
	}

    //前端配置文件检查
    mpath_config := filepath.Join(mpath, "web", "js", "config.json")
    if mystruct.Exists(mpath_config) == false {
    	var map_list = make(map[string][]string)
    	map_list["string"] = []string{"包含", "不包含", "等于", "不等于"}
    	map_list["int"] = []string{"大于","小于","等于"}
    	map_list["bool"] = []string{"真","假"}
    	map_list["tag"] = []string{"等于", "不等于"}
    	map_list["file"] = []string{"包含", "不包含"}
    	map_list["but"] = []string{"等于", "不等于"}
    	map_list["prgs"] = []string{""}
    	map_list["table"] = []string{""}
    	map_list["word"] = []string{"包含", "不包含", "等于", "不等于"}
    	map_list["pack"] = []string{"包含", "不包含", "等于", "不等于"}
    	data := map[string]interface{}{
	        "completed": map_list,
	    }
	    file, err := os.Create(mpath_config); 
	    if err != nil {
	    	mylog.ErrLog(fmt.Sprintf("创建配置文件 %s 失败: %s", mpath_config, err.Error()), Mtoken.Log_Path)
	    	panic(fmt.Errorf("创建配置文件 %s 失败: %w", mpath_config, err))
	    }
	    encoder := json.NewEncoder(file)
	    encoder.SetIndent("", "  ")
	    if err = encoder.Encode(data); err != nil {
	    	mylog.ErrLog(fmt.Sprintf("写入配置文件 %s 失败: %s", mpath_config, err.Error()), Mtoken.Log_Path)
	    	panic(fmt.Errorf("写入配置文件 %s 失败: %w", mpath_config, err))
	    }
	    file.Close()
    }
}